import Vue from 'vue'
import Vuex from 'vuex'
import { getToken, setToken, removeToken } from '../utils/auth'
import { setUser, getUser, removeUser} from '../utils/user'
import { logout } from '../api/index'
import { Message } from 'element-ui'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    name: getUser(),
    token: getToken()
  },
  mutations: {
    SET_NAME: (state, name) => {
      setUser(name)
      state.name = name
    },
    SET_TOKEN: (state, token) => {
      setToken(token)
      state.token = token
    }
  },
  actions: {
    SET_NAME: (context, payload) => {
      context.commit('SET_NAME', payload)
    },
    SET_TOKEN: (context, payload) => {
      context.commit('SET_TOKEN', payload)
    },
    LOG_OUT({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN' , '')
          commit('SET_NAME' , '')
          removeToken()
          removeUser()
          Message.success('退出成功')
          resolve()
        }).catch(error => {
          Message.error('退出失败')
          reject(error)
        })
      })
    }
  },
  modules: {
  }
})
